package cn.edu.gzgs.service.impl;

import cn.edu.gzgs.entity.User;
import cn.edu.gzgs.entity.UserRole;
import cn.edu.gzgs.mapper.UserMapper;
import cn.edu.gzgs.mapper.UserRoleMapper;
import cn.edu.gzgs.mapper.RoleMenuMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections; // 对于空的权限列表
import java.util.List;
import java.util.Set;
import java.util.ArrayList;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;
    private final UserRoleMapper userRoleMapper;
    private final RoleMenuMapper roleMenuMapper;

    @Autowired
    public UserDetailsServiceImpl(UserMapper userMapper, UserRoleMapper userRoleMapper, RoleMenuMapper roleMenuMapper) {
        this.userMapper = userMapper;
        this.userRoleMapper = userRoleMapper;
        this.roleMenuMapper = roleMenuMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String userNo) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_no", userNo);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 获取角色ID
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id", user.getId()).select("role_id");
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
        Set<String> roleIds = userRoles.stream()
                                     .map(userRole -> String.valueOf(userRole.getRoleId()))
                                     .collect(Collectors.toSet());

        // 获取角色类型
        Set<Integer> roleTypes = Collections.emptySet();
        if (roleIds != null && !roleIds.isEmpty()) {
            roleTypes = roleMenuMapper.findRoleTypesByRoleIds(new ArrayList<>(roleIds));
        }
        // 转成Authorities
        List<GrantedAuthority> authorities = roleTypes.stream()
                .map(type -> new SimpleGrantedAuthority("ROLE_" + type))
                .collect(Collectors.toList());

        return new org.springframework.security.core.userdetails.User(
                user.getUserNo(),
                user.getPassword(),
                authorities
        );
    }

} 